<<<<<<< HEAD
<<<<<<< HEAD
// pages/me/me.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
=======
import uCharts from '../../components/qiun-wx-charts/u-charts'; // 确保路径正确

// 定义 uChartsInstance 作为全局变量
var uChartsInstance = {};

Page({
  data: {
    cWidth: 750,
    cHeight: 500
  },
  onReady() {
    //这里的第一个 750 对应 css .charts 的 width
    const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
    //这里的 500 对应 css .charts 的 height
    const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
    this.setData({ cWidth, cHeight });
    this.getServerData();
    this.getNewChartData(); // 获取新柱状图的数据
  },
  getNewChartData() {
    // 模拟从服务器获取新柱状图的数据
    setTimeout(() => {
      let newRes = {
        categories: ["2018", "2019", "2020", "2021", "2022", "2023"],
        series: [
          {
            name: "目标值",
            data: [35, 36, 31, 33, 13, 34]
          },
          {
            name: "完成量",
            data: [18, 27, 21, 24, 6, 28]
          }
        ]
      };
      this.drawNewChart('canvas-2d', newRes); // 绘制新柱状图
    }, 500);
  },
  getServerData() {
    //模拟从服务器获取数据时的延时
    setTimeout(() => {
      //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
      let res = {
            categories: ["2018","2019","2020","2021","2022","2023"],
            series: [
              {
                name: "目标值",
                data: [35,36,31,33,13,34]
              },
              {
                name: "完成量",
                data: [18,27,21,24,6,28]
              }
            ]
          };
      this.drawCharts('canvas-2d', res);
    }, 500);
  },
  getServerData() {
    //模拟从服务器获取数据时的延时
    setTimeout(() => {
      //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
      let res = {
            series: [
              {
                data: [{"name":"一班","value":50},{"name":"二班","value":30},{"name":"三班","value":20},{"name":"四班","value":18,"labelText":"四班:18人"},{"name":"五班","value":8}]
              }
            ]
          };
      this.drawCharts('canvas-2d', res);
    }, 500);
  },
  
  drawNewChart(id, data) {
    // 绘制新柱状图的逻辑
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
      type: "column",
      context: ctx,
      width: this.data.cWidth,
      height: this.data.cHeight,
      categories: data.categories,
      series: data.series,
      animation: true,
      background: "#FFFFFF",
      color: ["#FAC858","#EE6666","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
      padding: [15,15,0,5],
      enableScroll: false,
      legend: {},
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        data: [
          {
            min: 0
          }
        ]
      },
      extra: {
        column: {
          type: "group",
          width: 30,
          activeBgColor: "#000000",
          activeBgOpacity: 0.08,
          linearType: "custom",
          seriesGap: 5,
          linearOpacity: 0.5,
          barBorderCircle: true,
          customColor: [
            "#FA7D8D",
            "#EB88E2"
          ]
=======
// pages/index/index.js
import uCharts from '../../components/qiun-wx-charts/u-charts';

var uChartsInstance = {};

Page({
  data: {
    selectedDate: [2024, 7], 
    multiDateOptions: [
      Array.from({ length: 2100 }, (_, i) => i + 0), // 年份
      Array.from({ length: 12 }, (_, i) => i + 0), // 月份
    ],
    cWidth: 750,
    cHeight: 500,
    localData: [],
    progressData: [
      { category: '餐饮', percent: 0, icon: '/staic/00 (2).png' },
      { category: '交通', percent: 0, icon: '/staic/00 (5).png' },
      { category: '服饰', percent: 0, icon: '/staic/001 (22).png' },
      { category: '购物', percent: 0, icon: '/staic/00 (3).png' },
      { category: '服务', percent: 0, icon: '/staic/001 (6).png' },
      { category: '教育', percent: 0, icon: '/staic/001 (7).png' },
      { category: '娱乐', percent: 0, icon: '/staic/001 (21).png' },
      { category: '运动', percent: 0, icon: '/staic/001 (23).png' },
      { category: '生活缴费', percent: 0, icon: '/staic/00 (6).png' },
      { category: '旅行', percent: 0, icon: '/staic/001 (10).png' },
      { category: '宠物', percent: 0, icon: '/staic/001 (3).png' },
      { category: '医疗', percent: 0, icon: '/staic/001 (20).png' },
      { category: '保险', percent: 0, icon: '/staic/001 (1).png' },
      { category: '公益', percent: 0, icon: '/staic/001 (24).png' },
      { category: '发红包', percent: 0, icon: '/staic/001 (5).png' },
      { category: '转账', percent: 0, icon: '/staic/001 (19).png' },
      { category: '亲属卡', percent: 0, icon: '/staic/001 (13).png' },
      { category: '其他', percent: 0, icon: '/staic/001 (12).png' },
      { category: '退还', percent: 0, icon: '/staic/001 (18).png' },
      { category: '请选择', percent: 0, icon: '/staic/请选择.png' },
      { category: '生意', percent: 0, icon: '/staic/请选择.png' },
      { category: '工资', percent: 0, icon: '/staic/请选择.png' },
      { category: '奖金', percent: 0, icon: '/staic/请选择.png' },
      { category: '其他人情', percent: 0, icon: '/staic/请选择.png' },
      { category: '收红包', percent: 0, icon: '/staic/请选择.png' },
      { category: '收转账', percent: 0, icon: '/staic/请选择.png' },
      { category: '商家转账', percent: 0, icon: '/staic/请选择.png' },
      { category: '退款', percent: 0, icon: '/staic/请选择.png' },
      { category: '理财', percent: 0, icon: '/staic/请选择.png' },
      { category: '借还款', percent: 0, icon: '/staic/请选择.png' },
      { category: '赠礼', percent: 0, icon: '/staic/请选择.png' },
      // 更多的类别...
    ],
    records:[],
    totalIncome: 0,
    totalExpense: 0,
  },
  prepareBarChartData: function (data) {
    // 返回一个包含 categories 和 series 的对象
    return data;
  },
  bindDateChange: function(e) {
    const selectedDate = e.detail.value;
    this.setData({
      selectedDate: selectedDate
    });

    // 调用方法来更新图表数据
    this.updateChartData(selectedDate);
  },
  onShow: function () {
    // 计算画布的宽度和高度
    const systemInfo = wx.getSystemInfoSync();
    const cWidth = 750 / 750 * systemInfo.windowWidth;
    const cHeight = 500 / 750 * systemInfo.windowWidth;

    // 从本地缓存加载数据
    const records = wx.getStorageSync('records') || [];

    // 更新页面数据
    this.setData({
      cWidth,
      cHeight,
      localData: records,
    });

    // 更新进度条数据
    this.updateProgressData(records);

    // 清除之前的图表实例（如果有的话）
    if (uChartsInstance['xun']) {
      // 如果 destroy 方法存在，则使用它
      if (typeof uChartsInstance['xun'].destroy === 'function') {
        uChartsInstance['xun'].destroy();
      } else {
        // 如果不存在 destroy 方法，则尝试清除画布上下文
        const ctx = wx.createCanvasContext('xun', this);
        ctx.clearRect(0, 0, cWidth, cHeight);
        ctx.draw();
      }
    }
    const chartData = this.prepareBarChartData(records);
    this.setData({
      totalExpense: chartData.totalExpense,
      totalIncome: chartData.totalIncome
    });
    // 使用本地数据绘制图表
    this.drawCharts('xun', this.prepareChartData(records));
    this.fetchAndDrawData();
  },
  updateProgressData: function (localData) {
    // 计算各类别总金额
    const categorySums = localData.reduce((acc, item) => {
      acc[item.category] = (acc[item.category] || 0) + item.amount;
      return acc;
    }, {});
  
    // 设定一个固定的最大值，用于映射金额到进度条的百分比
    const fixedMaxAmount = 10000;
  
    // 更新 progressData 数组的 percent 字段
    this.data.progressData.forEach(item => {
      if (categorySums[item.category]) {
        item.percent = Math.min((categorySums[item.category] || 0) * 100 / fixedMaxAmount, 100);
      } else {
        item.percent = 0;
      }
    });
  
    // 更新数据
    this.setData({
      progressData: this.data.progressData,
    });
  },
  updateChartData: function(selectedDate) {
    const year = this.data.multiDateOptions[0][selectedDate[0]];
    const month = this.data.multiDateOptions[1][selectedDate[1]];
  
    // 从本地存储加载数据
    const records = wx.getStorageSync('records') || [];
  
    // 筛选出特定年月的数据
    const filteredRecords = records.filter(record => {
      const recordDate = new Date(record.date); // 假设 date 是一个日期字符串
      return recordDate.getFullYear() === parseInt(year) && recordDate.getMonth() + 1 === parseInt(month);
    });
  
    // 准备柱状图所需的数据
    const chartData = this.prepareBarChartData(filteredRecords);
    // 准备饼状图所需的数据
    const charData = this.prepareChartData(filteredRecords);

    // 绘制饼状图
   this.drawCharts('xun', charData);
    // 绘制柱状图
    this.drawBarChart('link', chartData);
    //绘制进度条
    this.updateProgressData(filteredRecords);
    this.setData({
      totalExpense: chartData.totalExpense,
      totalIncome: chartData.totalIncome
    });
  },

  fetchAndDrawData: function() {
    setTimeout(() => {
      // 从本地存储加载数据
      const records = wx.getStorageSync('records') || [];
      
      // 准备柱状图所需的数据
      const chartData = this.prepareBarChartData(records);
      
      // 绘制柱状图
      this.drawBarChart('link', chartData);
    }, 500);
  },
  
  prepareBarChartData: function (records) {
    // 初始化分类和系列数据
    let categories = [];
    let seriesData = {
      '支出': [],
      '收入': []
    };
  
    // 遍历记录并填充数据
    records.forEach(record => {
      if (!categories.includes(record.category)) {
        categories.push(record.category);
      }
      seriesData['收入'][categories.indexOf(record.category)] = 0;
      // 添加数据到支出
      const index = categories.indexOf(record.category);
      if (index >= 0) {
        if (seriesData['支出'][index] === undefined) {
          seriesData['支出'][index] = 0;
        }
        if (record.type === '支出') {
          seriesData['支出'][index] += record.amount;
        }
  
        // 添加数据到收入
        if (record.type === '收入' || record.type === 'income') { // 修改了这里
          if (seriesData['收入'][index] === undefined) {
            seriesData['收入'][index] = 0;
          }
          seriesData['收入'][index] += record.amount;
        }
      }
    });
  
    // 计算总支出和总收入
    let totalExpense = 0;
    let totalIncome = 0;
    seriesData['支出'].forEach((amount, i) => {
      totalExpense += amount;
      if (seriesData['收入'][i] !== undefined) {
        totalIncome += seriesData['收入'][i];
      }
    });
  
    // 将数据整理为柱状图所需的格式
    const series = [
      { name: '支出', data: seriesData['支出'] },
      { name: '收入', data: seriesData['收入'] }
    ];
  
    // 返回完整的数据对象
    return {
      categories: categories,
      series: series,
      totalExpense: totalExpense,
      totalIncome: totalIncome
    };
  },
  prepareChartData: function (localData) {
    // 使用 localData 来访问页面的数据
    const dataMap = localData.reduce((acc, item) => {
      const label = `${item.category} - ${item.type === 'income' ? '收入' : '支出'}`;
      if (!acc[label]) {
        acc[label] = 0;
      }
      acc[label] += item.amount;
      return acc;
    }, {});

    return Object.entries(dataMap).map(([name, value]) => {
      return { name: name, value: value };
    });
  },
  
  drawCharts: function (id, chartData) {
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
      type: 'pie',
      context: ctx,
      width: this.data.cWidth,
      height: this.data.cHeight,
      series: [{
        data: chartData
      }],
      animation: true,
      background: '#FFFFFF',
      color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
      padding: [15, 15, 0, 5],
      enableScroll: false,
      extra: {
        pie: {
          activeOpacity: 0.5,
          activeRadius: 10,
          offsetAngle: 0,
          labelWidth: 15,
          border: false,
          borderWidth: 3,
          borderColor: '#FFFFFF'
>>>>>>> 0856d6b... 07-25完成小程序
        }
      }
    });
  },
<<<<<<< HEAD
  drawCharts(id,data){
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
        type: "bar",
        context: ctx,
        width: this.data.cWidth,
        height: this.data.cHeight,
        categories: data.categories,
        series: data.series,
        animation: true,
        background: "#FFFFFF",
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [15,30,0,5],
        enableScroll: false,
        legend: {},
        xAxis: {
          boundaryGap: "justify",
          disableGrid: false,
          min: 0,
          axisLine: false,
          max: 40
        },
        yAxis: {},
        extra: {
          bar: {
            type: "group",
            width: 30,
            meterBorde: 1,
            meterFillColor: "#FFFFFF",
            activeBgColor: "#000000",
            activeBgOpacity: 0.08,
            linearType: "custom",
            barBorderCircle: true,
            seriesGap: 2,
            categoryGap: 2
          }
        }
      });
  },
  drawCharts(id,data){
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
        type: "ring",
        context: ctx,
        width: this.data.cWidth,
        height: this.data.cHeight,
        series: data.series,
        animation: true,
        rotate: false,
        rotateLock: false,
        background: "#FFFFFF",
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [5,5,5,5],
        dataLabel: true,
        enableScroll: false,
        legend: {
          show: true,
          position: "right",
          lineHeight: 25
        },
        title: {
          name: "收益率",
          fontSize: 15,
          color: "#666666"
        },
        subtitle: {
          name: "70%",
          fontSize: 25,
          color: "#7cb5ec"
        },
        extra: {
          ring: {
            ringWidth: 60,
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: true,
            borderWidth: 3,
            borderColor: "#FFFFFF"
          }
        }
      });
  },
  tap(e) {
    // 处理图表的触摸事件
    if (uChartsInstance[e.target.id]) {
      uChartsInstance[e.target.id].touchLegend(e);
      uChartsInstance[e.target.id].showToolTip(e);
    }
  }
});
>>>>>>> d89ffbc... 07-23统计图
=======
  drawBarChart: function (id, chartData) {
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
      type: 'bar',
      context: ctx,
      width: this.data.cWidth,
      height: this.data.cHeight,
      series: chartData.series,
      categories: chartData.categories,
      animation: true,
      background: '#FFFFFF',
      color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
      padding: [5, 5, 5, 5],
      enableScroll: false,
      extra: {
        bar: {
          width: 10,
          spacing: 2,
          borderRadius: 5,
          stack: true,
        }
      }
    });
  },
  tap: function (e) {
    uChartsInstance[e.target.id].touchLegend(e);
    uChartsInstance[e.target.id].showToolTip(e);
  }
});
>>>>>>> 0856d6b... 07-25完成小程序
